package com.clei.netty.sync.client;

import com.clei.netty.sync.decoder.ByteToMsgDecoder;
import com.clei.netty.sync.dto.ClientParam;
import com.clei.netty.sync.encoder.MsgToByteEncoder;
import com.clei.utils.PrintUtil;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * file sync client initializer
 *
 * @author Y
 * @date 2024-08-14
 */
public class FileSyncClientInitializer extends ChannelInitializer<SocketChannel> {

    /**
     * 客户端参数
     */
    private final ClientParam clientParam;

    public FileSyncClientInitializer(ClientParam clientParam) {
        this.clientParam = clientParam;
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        PrintUtil.log("initChannel");
        ChannelPipeline pipeline = ch.pipeline();
        // 字段长度解码器
        LengthFieldBasedFrameDecoder lengthFieldDecoder = new LengthFieldBasedFrameDecoder(1048576, 0, 4, -4, 0);
        pipeline.addLast("lengthFieldDecoder", lengthFieldDecoder);
        // message <-> byte
        pipeline.addLast("decoder", new ByteToMsgDecoder());
        pipeline.addLast("encoder", new MsgToByteEncoder());
        pipeline.addLast("handler", new FileSyncClientHandler(this.clientParam));
    }
}
